<!-- 客服工作台 -->
<template>
	<view class="workbench-container">
		<!-- 状态栏 -->
			<view class="status-bar">
				<view class="status-info">
				<text class="status-text">当前状态：</text>
				<text :class="['status-value', isOnline ? 'online' : 'offline']">
					{{ isOnline ? '在线' : '离线' }}
				</text>
				</view>
			<button 
				class="status-btn" 
				:class="isOnline ? 'offline-btn' : 'online-btn'"
				@tap="toggleStatus"
			>
				{{ isOnline ? '切换离线' : '切换在线' }}
			</button>
			</view>
			
		<!-- 主内容区 -->
		<view class="main-content">
			<!-- 会话列表 -->
			<view class="session-list">
				<view class="list-header">
					<text class="title">当前会话</text>
					<text class="count">({{ activeSessions.length }})</text>
				</view>
				<scroll-view class="list-content" scroll-y>
					<view 
						v-for="session in activeSessions" 
						:key="session.id"
						:class="['session-item', currentSession?.id === session.id ? 'active' : '']"
						@tap="selectSession(session)"
					>
						<view class="user-info">
							<image class="avatar" :src="session.userAvatar" mode="aspectFill"></image>
							<view class="info">
								<text class="name">{{ session.userName }}</text>
								<text class="last-message">{{ session.lastMessage }}</text>
			</view>
					</view>
						<view class="session-status">
							<text class="time">{{ session.lastMessageTime }}</text>
							<view class="unread" v-if="session.unreadCount > 0">
								{{ session.unreadCount }}
				</view>
					</view>
				</view>
			</scroll-view>
		</view>
		
			<!-- 聊天区域 -->
		<view class="chat-area">
			<template v-if="currentSession">
					<!-- 聊天头部 -->
				<view class="chat-header">
						<view class="user-info">
							<image class="avatar" :src="currentSession.userAvatar" mode="aspectFill"></image>
							<view class="info">
								<text class="name">{{ currentSession.userName }}</text>
								<text class="status">正在输入...</text>
						</view>
					</view>
					<view class="header-actions">
							<button class="action-btn" @tap="handleTransfer">转接</button>
							<button class="action-btn" @tap="handleEnd">结束</button>
					</view>
				</view>
				
					<!-- 聊天内容 -->
					<scroll-view 
						class="chat-content" 
						scroll-y 
						:scroll-top="scrollTop"
						@scrolltoupper="loadMoreMessages"
					>
						<view class="message-list">
							<view 
								v-for="(message, index) in messages" 
								:key="index"
								:class="['message-item', message.isUser ? 'user-message' : 'service-message']"
							>
								<image 
									class="avatar" 
									:src="message.isUser ? currentSession.userAvatar : serviceAvatar" 
									mode="aspectFill"
								></image>
								<view class="message-content">
									<text class="message-text">{{ message.content }}</text>
									<text class="message-time">{{ message.time }}</text>
									</view>
							</view>
						</view>
					</scroll-view>
					
					<!-- 输入区域 -->
					<view class="chat-input">
						<view class="input-tools">
							<button class="tool-btn" @tap="showQuickReplies">快捷回复</button>
							<button class="tool-btn" @tap="showTemplates">模板</button>
						</view>
						<view class="input-box">
							<textarea 
								class="input-area" 
								v-model="inputMessage" 
								placeholder="请输入消息" 
								@confirm="sendMessage"
							></textarea>
							<button class="send-btn" @tap="sendMessage">发送</button>
							</view>
							</view>
				</template>

				<!-- 无会话提示 -->
				<view v-else class="no-session">
					<image class="empty-icon" src="/static/images/empty.png" mode="aspectFit"></image>
					<text class="empty-text">暂无进行中的会话</text>
						</view>
						</view>
					</view>
					
		<!-- 快捷回复弹窗 -->
		<view class="quick-reply-popup" v-if="showQuickReply">
			<view class="popup-content">
				<view class="popup-header">
					<text class="title">快捷回复</text>
					<text class="close" @tap="closeQuickReply">×</text>
				</view>
				<scroll-view class="reply-list" scroll-y>
					<view 
						v-for="reply in quickReplies" 
						:key="reply.id"
								  class="reply-item"
						@tap="selectQuickReply(reply)"
					>
						<text class="reply-text">{{ reply.content }}</text>
						</view>
					</scroll-view>
			</view>
				</view>
				
		<!-- 模板弹窗 -->
		<view class="template-popup" v-if="showTemplate">
			<view class="popup-content">
				<view class="popup-header">
					<text class="title">消息模板</text>
					<text class="close" @tap="closeTemplate">×</text>
							</view>
				<scroll-view class="template-list" scroll-y>
					<view 
						v-for="template in templates" 
						:key="template.id"
						class="template-item"
						@tap="selectTemplate(template)"
					>
						<text class="template-text">{{ template.content }}</text>
						</view>
					</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
import { 
	getServiceStatus,
	updateServiceStatus,
	getActiveSessions,
	loadMessages,
	sendMessage,
	endSession,
	getQuickReplies,
	getTemplates
} from '@/api/chat';

export default {
	data() {
		return {
			isOnline: false,
			activeSessions: [],
			currentSession: null,
			messages: [],
			inputMessage: '',
			serviceAvatar: '/static/images/service-avatar.png',
			scrollTop: 0,
			loading: false,
			hasMore: true,
			showQuickReply: false,
			showTemplate: false,
			quickReplies: [],
			templates: []
		};
	},

	onLoad() {
		this.initWorkbench();
	},

	methods: {
		// 初始化工作台
		async initWorkbench() {
			try {
				// 获取客服状态
				const status = await getServiceStatus();
				this.isOnline = status === 'ONLINE';
				
				// 加载会话列表
				this.loadActiveSessions();
				
				// 加载快捷回复
				this.loadQuickReplies();
				
				// 加载模板
				this.loadTemplates();
			} catch (error) {
				console.error('初始化工作台失败:', error);
				uni.showToast({
					title: '初始化工作台失败',
					icon: 'none'
				});
		}
	},
	
			// 切换在线状态
	async toggleStatus() {
		try {
			const newStatus = this.isOnline ? 'OFFLINE' : 'ONLINE';
			await updateServiceStatus(newStatus);
			this.isOnline = !this.isOnline;
			
			uni.showToast({
				title: this.isOnline ? '已切换为在线' : '已切换为离线',
				icon: 'success'
			});
		} catch (error) {
			console.error('切换状态失败:', error);
			uni.showToast({
				title: '切换状态失败',
				icon: 'none'
			});
		}
	},
		
		// 加载会话列表
		async loadActiveSessions() {
			try {
				const sessions = await getActiveSessions();
				this.activeSessions = sessions;
			} catch (error) {
				console.error('加载会话列表失败:', error);
				uni.showToast({
					title: '加载会话列表失败',
					icon: 'none'
				});
			}
		},
		
		// 选择会话
		async selectSession(session) {
			this.currentSession = session;
			this.messages = [];
			this.hasMore = true;
			this.loadMessages();
		},
		
		// 加载消息
		async loadMessages() {
			if (this.loading || !this.hasMore) return;
			
			this.loading = true;
			try {
				const lastMessage = this.messages[0];
				const beforeMessageId = lastMessage ? lastMessage.id : null;
				
				const response = await loadMessages(
					this.currentSession.id,
					beforeMessageId
				);
				
				if (response.records) {
					this.messages = [...response.records, ...this.messages];
					this.hasMore = response.records.length === response.size;
				}
			} catch (error) {
				console.error('加载消息失败:', error);
				uni.showToast({
					title: '加载消息失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 发送消息
		async sendMessage() {
			if (!this.inputMessage.trim()) return;
			
			try {
			const message = {
					content: this.inputMessage,
					sessionId: this.currentSession.id,
					isUser: false,
					time: new Date().toLocaleTimeString()
				};
				
				await sendMessage({
					sessionId: this.currentSession.id,
					content: this.inputMessage
				});
			
				this.messages.push(message);
				this.inputMessage = '';
				this.scrollToBottom();
			} catch (error) {
				console.error('发送消息失败:', error);
				uni.showToast({
					title: '发送消息失败',
					icon: 'none'
				});
			}
		},

		// 结束会话
		async handleEnd() {
			uni.showModal({
				title: '提示',
				content: '确定要结束当前会话吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await endSession(this.currentSession.id);
							
							// 更新会话列表
							this.activeSessions = this.activeSessions.filter(
								session => session.id !== this.currentSession.id
							);
							
							// 清空当前会话
						this.currentSession = null;
							this.messages = [];
							
							uni.showToast({
								title: '会话已结束',
								icon: 'success'
							});
						} catch (error) {
							console.error('结束会话失败:', error);
							uni.showToast({
								title: '结束会话失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 转接会话
		handleTransfer() {
			// TODO: 实现转接功能
			uni.showToast({
				title: '转接功能开发中',
				icon: 'none'
			});
		},
		
		// 加载快捷回复
		async loadQuickReplies() {
			try {
				const replies = await getQuickReplies();
				this.quickReplies = replies;
			} catch (error) {
				console.error('加载快捷回复失败:', error);
			}
		},

		// 加载模板
		async loadTemplates() {
			try {
				const templates = await getTemplates();
				this.templates = templates;
			} catch (error) {
				console.error('加载模板失败:', error);
					}
		},

		// 显示快捷回复
		showQuickReplies() {
			this.showQuickReply = true;
		},
		
		// 关闭快捷回复
		closeQuickReply() {
			this.showQuickReply = false;
		},
		
		// 选择快捷回复
		selectQuickReply(reply) {
			this.inputMessage = reply.content;
			this.closeQuickReply();
		},
		
		// 显示模板
		showTemplates() {
			this.showTemplate = true;
		},
		
		// 关闭模板
		closeTemplate() {
			this.showTemplate = false;
		},
		
		// 选择模板
		selectTemplate(template) {
			this.inputMessage = template.content;
			this.closeTemplate();
		},
		
		// 滚动到底部
		scrollToBottom() {
			setTimeout(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.chat-content').boundingClientRect();
				query.exec((res) => {
					if (res[0]) {
						this.scrollTop = res[0].height;
				}
				});
			}, 100);
		},

		// 加载更多消息
		loadMoreMessages() {
			this.loadMessages();
				}
	}
};
</script>

<style lang="scss">
.workbench-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}
		
		.status-bar {
				display: flex;
				justify-content: space-between;
				align-items: center;
	padding: 20rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
				
	.status-info {
				.status-text {
			font-size: 28rpx;
					color: #666;
				}

		.status-value {
			font-size: 28rpx;
			font-weight: bold;

			&.online {
				color: #52c41a;
			}

			&.offline {
				color: #999;
			}
		}
	}

	.status-btn {
		font-size: 28rpx;
		padding: 10rpx 30rpx;
		border-radius: 30rpx;

		&.online-btn {
			background-color: #52c41a;
			color: #fff;
				}

		&.offline-btn {
			background-color: #ff4d4f;
			color: #fff;
		}
	}
}

.main-content {
	flex: 1;
	display: flex;
	overflow: hidden;
		}
		
.session-list {
	width: 400rpx;
	background-color: #fff;
	border-right: 1rpx solid #eee;
	display: flex;
	flex-direction: column;
				
	.list-header {
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.count {
			font-size: 28rpx;
			color: #999;
			margin-left: 10rpx;
			}
		}
		
	.list-content {
			flex: 1;
		overflow-y: auto;
	}
			
			.session-item {
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
				cursor: pointer;

		&:hover {
			background-color: #f5f5f5;
				}
				
		&.active {
			background-color: #e6f7ff;
				}
				
		.user-info {
					display: flex;
			align-items: center;
			margin-bottom: 10rpx;
					
			.avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 20rpx;
			}

			.info {
				flex: 1;
				overflow: hidden;

				.name {
					font-size: 28rpx;
						font-weight: bold;
					color: #333;
					margin-bottom: 4rpx;
					}
					
				.last-message {
					font-size: 24rpx;
						color: #999;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
					}
				}
				
		.session-status {
					display: flex;
					justify-content: space-between;
					align-items: center;

			.time {
				font-size: 24rpx;
				color: #999;
					}
					
			.unread {
				min-width: 32rpx;
				height: 32rpx;
				line-height: 32rpx;
				text-align: center;
						background-color: #ff4d4f;
						color: #fff;
				border-radius: 16rpx;
				font-size: 24rpx;
				padding: 0 8rpx;
				}
			}
		}
	}
	
	.chat-area {
		flex: 1;
		display: flex;
		flex-direction: column;
	background-color: #fff;
}
		
		.chat-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
 padding: 20rpx;
 border-bottom: 1rpx solid #eee;
			
 .user-info {
				display: flex;
				align-items: center;

	 .avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			margin-right: 20rpx;
		}

		.info {
			.name {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
					}
					
			.status {
				font-size: 24rpx;
				color: #999;
				margin-top: 4rpx;
					}
				}
			}
			
			.header-actions {
		display: flex;
		gap: 20rpx;

		.action-btn {
			font-size: 28rpx;
			padding: 10rpx 30rpx;
			border-radius: 30rpx;
			background-color: #f5f5f5;
			color: #666;

			&:hover {
				background-color: #e6f7ff;
				color: #1890ff;
					}
				}
			}
		}
		
.chat-content {
			flex: 1;
 padding: 20rpx;
	overflow-y: auto;
			
			.message-list {
				.message-item {
					display: flex;
			margin-bottom: 30rpx;
					
			&.user-message {
						flex-direction: row-reverse;
						
						.message-content {
					margin-right: 20rpx;
					margin-left: 0;
					background-color: #e6f7ff;
								color: #333;
						}
					}
					
			&.service-message {
					.message-content {
					margin-left: 20rpx;
					margin-right: 0;
					background-color: #f5f5f5;
					color: #333;
				}
			}

			.avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
			}

			.message-content {
				max-width: 60%;
				padding: 20rpx;
				border-radius: 10rpx;
				box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
						
						.message-text {
					font-size: 28rpx;
							line-height: 1.5;
						}
						
						.message-time {
					font-size: 24rpx;
							color: #999;
					margin-top: 10rpx;
				}
						}
					}
				}
			}
			
.chat-input {
 padding: 20rpx;
	border-top: 1rpx solid #eee;

 .input-tools {
						display: flex;
		gap: 20rpx;
		margin-bottom: 20rpx;
						
		.tool-btn {
			font-size: 28rpx;
			padding: 10rpx 30rpx;
			border-radius: 30rpx;
			background-color: #f5f5f5;
							color: #666;

			&:hover {
				background-color: #e6f7ff;
				color: #1890ff;
			}
		}
	}

 .input-box {
				display: flex;
		align-items: flex-end;
		gap: 20rpx;
				
		.input-area {
			flex: 1;
			height: 160rpx;
			padding: 20rpx;
			border: 1rpx solid #ddd;
			border-radius: 10rpx;
			font-size: 28rpx;
			line-height: 1.5;
		}

		.send-btn {
			width: 120rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: #1890ff;
			color: #fff;
			border-radius: 40rpx;
			font-size: 28rpx;
					}
				}
			}
			
.no-session {
				flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background-color: #fff;

 .empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

 .empty-text {
		font-size: 28rpx;
		color: #999;
			}
		}
		
.quick-reply-popup,
.template-popup {
			position: fixed;
 top: 0;
 left: 0;
	right: 0;
	bottom: 0;
 background-color: rgba(0, 0, 0, 0.5);
			display: flex;
	justify-content: center;
	align-items: center;
			
 .popup-content {
		width: 80%;
		max-height: 80%;
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;

		.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
		 padding: 20rpx;
			border-bottom: 1rpx solid #eee;

			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
				
				.close {
				font-size: 40rpx;
					color: #999;
					cursor: pointer;
				}
			}
			
		.reply-list,
		.template-list {
			max-height: 600rpx;
			padding: 20rpx;

			.reply-item,
			.template-item {
				padding: 20rpx;
				border-bottom: 1rpx solid #eee;
						cursor: pointer;
						
						&:hover {
							background-color: #f5f5f5;
						}
						
				.reply-text,
				.template-text {
					font-size: 28rpx;
					color: #333;
					line-height: 1.5;
				}
			}
		}
	}
}
</style> 